package org.microframework.cloud.auth.controller;

import java.io.IOException;
import java.awt.image.BufferedImage;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import org.microframework.base.core.domain.R;
import org.microframework.base.core.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import javax.imageio.ImageIO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;

/**
 * 登录控制器 等保要求：提供安全的登录页面和验证码功能
 */
@Tag(name = "登录管理")
@RequiredArgsConstructor
@Controller
public class LoginController {

	private final DefaultKaptcha kaptcha;

	@Autowired
	private RedisService redisService;

	/**
	 * 登录页面
	 */
	@GetMapping("/login")
	public String login() {
		return "login";
	}

	/**
	 * 生成验证码 等保要求：提供验证码功能，防止暴力破解
	 */
	@Operation(summary = "获取验证码")
	@GetMapping("/captcha")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 生成验证码文本
		String code = kaptcha.createText();

		// 生成唯一标识
		String captchaKey = UUID.randomUUID().toString();

		// 存储验证码到Redis，有效期5分钟
		redisService.setCacheObject("captcha:" + captchaKey, code, 5L, TimeUnit.MINUTES);

		// 设置验证码标识到Cookie
		response.addCookie(new jakarta.servlet.http.Cookie("captchaKey", captchaKey));

		// 根据文本生成验证码图片
		BufferedImage image = kaptcha.createImage(code);

		// 输出验证码图片
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		ImageIO.write(image, "jpg", response.getOutputStream());
		response.getOutputStream().flush();
	}

	/**
	 * 验证验证码
	 */
	@Operation(summary = "验证验证码")
	@PostMapping("/captcha/verify")
	@ResponseBody
	public R<Void> verifyCaptcha(String code, String captchaKey) {
		// 从Redis获取验证码
		String storedCode = redisService.getCacheObject("captcha:" + captchaKey);

		// 验证码不存在或已过期
		if (storedCode == null) {
			return R.fail("验证码已过期");
		}

		// 验证码错误
		if (!storedCode.equalsIgnoreCase(code)) {
			return R.fail("验证码错误");
		}

		// 验证通过后删除验证码
		redisService.deleteObject("captcha:" + captchaKey);

		return R.ok();
	}

	/**
	 * OAuth2授权确认页面
	 */
	@GetMapping("/oauth2/consent")
	public String consent(Model model, HttpServletRequest request) {
		// 获取授权请求参数
		String clientId = request.getParameter("client_id");
		String scope = request.getParameter("scope");

		// 传递参数到同意页面
		model.addAttribute("clientId", clientId);
		model.addAttribute("scopes", scope != null ? scope.split(" ") : new String[0]);
		model.addAttribute("year", java.time.Year.now().getValue());

		return "consent";
	}
}